package com.scholarship.system.controller;

import com.scholarship.system.common.dto.Result;
import com.scholarship.system.entity.Student;
import com.scholarship.system.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生管理控制器
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    /**
     * 获取学生列表
     * 
     * @param advisorId 导师ID，为空则获取当前导师下的学生
     * @param keyword   关键字搜索（学号/姓名）
     * @return 学生列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<List<Map<String, Object>>> getStudentList(
            @RequestParam(required = false) Long advisorId,
            @RequestParam(required = false) String keyword) {
        try {
            logger.info("获取学生列表: advisorId={}, keyword={}", advisorId, keyword);
            // 如果没有指定导师ID，则使用当前登录导师的ID
            if (advisorId == null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                String username = authentication.getName();
                logger.info("当前登录用户: {}", username);

                // 记录认证信息和权限
                logger.info("认证信息: {}", authentication);
                logger.info("认证权限: {}", authentication.getAuthorities());
            }

            return studentService.getStudentList(advisorId, keyword);
        } catch (Exception e) {
            logger.error("获取学生列表异常", e);
            return Result.error("获取学生列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取学生详情
     * 
     * @param id 学生ID
     * @return 学生详情
     */
    @GetMapping("/detail/{id}")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Map<String, Object>> getStudentDetail(@PathVariable Long id) {
        try {
            logger.info("获取学生详情: id={}", id);
            return studentService.getStudentDetail(id);
        } catch (Exception e) {
            logger.error("获取学生详情异常", e);
            return Result.error("获取学生详情失败: " + e.getMessage());
        }
    }

    /**
     * 添加学生
     * 
     * @param params 包含学生信息和用户信息的参数
     * @return 结果
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> addStudent(@RequestBody Map<String, Object> params) {
        try {
            logger.info("添加学生: {}", params);
            // 从params中提取student信息和userInfo信息
            Student student = new Student();
            student.setStudentId((String) params.get("studentId"));
            student.setCollege((String) params.get("college"));
            student.setMajor((String) params.get("major"));
            student.setGrade((String) params.get("grade"));
            student.setClassName((String) params.get("className"));

            // 安全地处理entryYear
            Object entryYearObj = params.get("entryYear");
            if (entryYearObj != null) {
                try {
                    if (entryYearObj instanceof Integer) {
                        student.setEntryYear((Integer) entryYearObj);
                    } else if (entryYearObj instanceof String) {
                        student.setEntryYear(Integer.parseInt((String) entryYearObj));
                    } else {
                        student.setEntryYear(Integer.parseInt(entryYearObj.toString()));
                    }
                } catch (NumberFormatException e) {
                    logger.error("入学年份格式错误: {}", entryYearObj, e);
                    return Result.error("入学年份格式错误");
                }
            }

            student.setEducationLevel((String) params.get("educationLevel"));

            // 安全地处理advisorId
            Object advisorIdObj = params.get("advisorId");
            if (advisorIdObj != null) {
                try {
                    if (advisorIdObj instanceof Long) {
                        student.setAdvisorId((Long) advisorIdObj);
                    } else if (advisorIdObj instanceof Integer) {
                        student.setAdvisorId(((Integer) advisorIdObj).longValue());
                    } else if (advisorIdObj instanceof String) {
                        student.setAdvisorId(Long.parseLong((String) advisorIdObj));
                    } else {
                        student.setAdvisorId(Long.parseLong(advisorIdObj.toString()));
                    }
                } catch (NumberFormatException e) {
                    logger.error("导师ID格式错误: {}", advisorIdObj, e);
                    return Result.error("导师ID格式错误");
                }
            }

            // 提取用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("name", params.get("name"));
            userInfo.put("gender", params.get("gender"));
            userInfo.put("phone", params.get("phone"));
            userInfo.put("email", params.get("email"));

            return studentService.addStudent(student, userInfo);
        } catch (Exception e) {
            logger.error("添加学生异常", e);
            return Result.error("添加学生失败: " + e.getMessage());
        }
    }

    /**
     * 更新学生
     * 
     * @param params 包含学生信息和用户信息的参数
     * @return 结果
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> updateStudent(@RequestBody Map<String, Object> params) {
        try {
            logger.info("更新学生: {}", params);
            // 从params中提取student信息和userInfo信息
            Student student = new Student();

            // 安全地处理学生ID
            Object idObj = params.get("id");
            if (idObj != null) {
                try {
                    if (idObj instanceof Long) {
                        student.setId((Long) idObj);
                    } else if (idObj instanceof Integer) {
                        student.setId(((Integer) idObj).longValue());
                    } else if (idObj instanceof String) {
                        student.setId(Long.parseLong((String) idObj));
                    } else {
                        student.setId(Long.parseLong(idObj.toString()));
                    }
                } catch (NumberFormatException e) {
                    logger.error("学生ID格式错误: {}", idObj, e);
                    return Result.error("学生ID格式错误");
                }
            } else {
                return Result.error("学生ID不能为空");
            }

            student.setStudentId((String) params.get("studentId"));
            student.setCollege((String) params.get("college"));
            student.setMajor((String) params.get("major"));
            student.setGrade((String) params.get("grade"));
            student.setClassName((String) params.get("className"));

            // 安全地处理entryYear
            Object entryYearObj = params.get("entryYear");
            if (entryYearObj != null) {
                try {
                    if (entryYearObj instanceof Integer) {
                        student.setEntryYear((Integer) entryYearObj);
                    } else if (entryYearObj instanceof String) {
                        student.setEntryYear(Integer.parseInt((String) entryYearObj));
                    } else {
                        student.setEntryYear(Integer.parseInt(entryYearObj.toString()));
                    }
                } catch (NumberFormatException e) {
                    logger.error("入学年份格式错误: {}", entryYearObj, e);
                    return Result.error("入学年份格式错误");
                }
            }

            student.setEducationLevel((String) params.get("educationLevel"));

            // 安全地处理advisorId
            Object advisorIdObj = params.get("advisorId");
            if (advisorIdObj != null) {
                try {
                    if (advisorIdObj instanceof Long) {
                        student.setAdvisorId((Long) advisorIdObj);
                    } else if (advisorIdObj instanceof Integer) {
                        student.setAdvisorId(((Integer) advisorIdObj).longValue());
                    } else if (advisorIdObj instanceof String) {
                        student.setAdvisorId(Long.parseLong((String) advisorIdObj));
                    } else {
                        student.setAdvisorId(Long.parseLong(advisorIdObj.toString()));
                    }
                } catch (NumberFormatException e) {
                    logger.error("导师ID格式错误: {}", advisorIdObj, e);
                    return Result.error("导师ID格式错误");
                }
            }

            // 提取用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("name", params.get("name"));
            userInfo.put("gender", params.get("gender"));
            userInfo.put("phone", params.get("phone"));
            userInfo.put("email", params.get("email"));

            return studentService.updateStudent(student, userInfo);
        } catch (Exception e) {
            logger.error("更新学生异常", e);
            return Result.error("更新学生失败: " + e.getMessage());
        }
    }

    /**
     * 删除学生
     * 
     * @param id 学生ID
     * @return 结果
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> deleteStudent(@PathVariable Long id) {
        try {
            logger.info("删除学生: id={}", id);
            return studentService.deleteStudent(id);
        } catch (Exception e) {
            logger.error("删除学生异常", e);
            return Result.error("删除学生失败: " + e.getMessage());
        }
    }

    /**
     * 分配导师
     * 
     * @param studentId 学生ID
     * @param advisorId 导师ID
     * @return 结果
     */
    @PutMapping("/assign")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> assignAdvisor(
            @RequestParam Long studentId,
            @RequestParam Long advisorId) {
        try {
            logger.info("分配导师: studentId={}, advisorId={}", studentId, advisorId);
            return studentService.assignAdvisor(studentId, advisorId);
        } catch (Exception e) {
            logger.error("分配导师异常", e);
            return Result.error("分配导师失败: " + e.getMessage());
        }
    }
}